<?php

namespace Biz\service\erp;

use Biz\model\GoodsSku;
use Biz\model\trade\OrderRemark;
use Biz\model\trade\ShopCourier;
use Biz\pockets\constInterface\PayConfig;
use Biz\service\trade\Order;
use Biz\service\trade\OrderPay;
use Biz\tools\ShopArea;
use Doraemon\tools\Log;

/**
 * @deprecated
 */
class Nippon
{
//    const TOKEN = 'a4b8063a4e7194c31ae6d872dc27e9c36922ab8f9005e4f6ca11b67d5038005b';//测试
//    const SHOP_ID = 1962205;

    const TOKEN = '43fcab918d9cffe6145eefca996e0b32fb7b9573a7568aac7a89399dc3c9939d';//线上
    const SHOP_ID = 8577931;

    const METHOD_MAP = [
        'logistics.offline.send' => 'send'
    ];
    const MEMBER_INFO = [
        'uname' => 'hhz',//用户名
        'name' => '住小帮',//真实姓名
        'mobile' => '16619891743',//手机号码
        'email' => '16619891743@163.com',//邮箱
        'alipay_no' => '18501911924',//支付宝账号
        'area_state' => '北京',//会员所在省
        'area_city' => '北京市',//会员所在市
        'area_district' => '朝阳区',//会员所在区县
    ];

    /**
     * 接口入口
     * @param $method
     * @param $params
     * @param $sign
     * @throws \Exception
     */
    public static function index($method, $params, $sign)
    {
        $callMethod = self::METHOD_MAP[$method] ?? '';

        if (!method_exists(self::class, $callMethod)) throw new \Exception("未定义的接口$method 调用方法$callMethod");

        $checkSign = self::gen_sign($params);

        if ($sign != $checkSign) throw new \Exception("sign校验错误 sign:$sign check:$checkSign");

        Log::info('立邦接口数据', compact('method', 'params', 'sign', 'checkSign'));

        call_user_func_array([self::class, $callMethod], [$params]);

    }

    /**
     * 发货接口
     * @param $params
     * @throws \Exception
     */
    public static function send($params)
    {
        $shopId = self::SHOP_ID;
        $orderNo = $params['order_bn'] ?? '';
        $logistic_code = $params['logistic_code'] ?? '';
        $express_no = $params['express_no'] ?? '';
        $goods = json_decode($params['goods'], true);

        $courierId = ShopCourier::get('courier_id', ['courierbird_code' => $logistic_code]);

        if (!$courierId) throw new \Exception('快递公司code不正确');

        $expressData['express_no'] = trim($express_no);

        if ($goods) {
            foreach ($goods as $v) {
                $content = '';
                try {
                    //
                    $bn = $v['bn'] ?? '';
                    $quantity = $v['quantity'] ?? 0;
                    if ($quantity <= 0) throw new \Exception('发货数量必须大于0');

                    $skuIds = GoodsSku::get('id', ['status' => GoodsSku::STATUS_PASSED, 'shop_id' => $shopId, 'sku_no' => $bn]);
                    if (!$skuIds) throw new \Exception('商品编码' . $bn . '有误,未找到对应关系');

                    Log::info('立邦接口发货数据', compact('shopId', 'orderNo', 'expressData', 'courierId', 'skuIds'));

                    $content = "sku:$skuIds 商家编码:$bn 发货数量:$quantity 快递单号:$express_no";
                    $postData['content'] = $content;

                    \Biz\module\Classes\mgt\Order::shipOrder($orderNo, $expressData, $shopId, $courierId, false, $skuIds);

                    Order::admSaveOrderRemark(0, $orderNo, $postData, OrderRemark::HHZ_REMARK_TYPE_API_APPEND);

                } catch (\Exception $e) {
                    $errMsg = $e->getMessage();

                    Log::info('立邦接口发货异常处理', compact('shopId', 'orderNo', 'expressData', 'courierId', 'skuIds', 'errMsg'));

                    if ($e->getCode() == 7777) {
                        Order::admSaveOrderRemark(0, $orderNo, $postData, OrderRemark::HHZ_REMARK_TYPE_API_APPEND);
                    } else {
                        throw $e;
                    }
                }

            }
        }
    }



    public static function gen_sign($params){
        return strtoupper(md5(strtoupper(md5(self::assemble($params))) . self::TOKEN));
    }

    public static function assemble($params)
    {
        if(!is_array($params))  return null;
        ksort($params, SORT_STRING);
        $sign = '';
        foreach($params as $key=>$val){
            if(is_null($val))   continue;
            if(is_bool($val))   $val = ($val) ? 1 : 0;
            $sign .= $key . (is_array($val) ? self::assemble($val) : $val);
        }
        return $sign;
    }

    /**
     * 调用立邦创建订单接口
     * @param $orderInfoList
     * @param $orderGoodsList
     */
    public static function addOrder($orderInfoList, $orderGoodsList)
    {
        $method = 'ome.order.add';
        if ($orderInfoList) {
            foreach ($orderInfoList as $order) {
                //过滤出立邦的订单
                if ($order['shop_id'] != self::SHOP_ID) continue;

                $order_no = $order['order_no'];
                $order_parent_no = $order['order_parent_no'];
                $consignee = [
                    'name' => $order['consignee_name'],//姓名
                    'mobile' => $order['consignee_phone'],//手机号
                    'area_state' => ShopArea::locationId2Name($order['consignee_province']),//省
                    'area_city' => ShopArea::locationId2Name($order['consignee_city']),//市
                    'area_district' => ShopArea::locationId2Name($order['consignee_area']),//区县
                    'addr' => $order['consignee_info_address'],//详细地址
                ];
                $payInfo = \Biz\model\trade\OrderPay::getPayInfoByOrderNo([$order_parent_no, $order_no]);
                $pay = $order['pay_amount'] - $order['shipping_amount'];

                $payments = [];
                $payWay = '';
                foreach ($payInfo as $v) {
                    $payWay = $v['pay_way'];
                    $payments[] = [
                        'trade_no' => $v['pay_no'],//支付单号
                        'pay_time' => $order['edittime'], //支付时间
                        'paymethod' => PayConfig::_PAY_WAYS_DESC[$v['pay_way']] ?? '', //支付方式名称 支付宝
                        'money' => $pay, //支付金额
                        'pay_bn' => $v['pay_way'], //支付方式编码 alipay
                    ];
                    break;
                }

                //商品信息
                $order_objects = [];
                $orderGoodsList = $order_no ? \Biz\model\trade\OrderGoods::getFieldsByOrderNo($order_no) : [];
                foreach ($orderGoodsList as $v) {
                    $amount = $v['goods_amount'];
                    $bn = GoodsSku::get('sku_no', ['id' => $v['sku_id']]);
                    $name = $v['title'] . " " . $v['sku_desc'];
                    $order_items = [
                        [
                            'bn' => $bn, //商品编号
                            'name' => $name, //商品名称
                            'price' => $v['buy_price'], //商品单价
                            'pmt_price' => bcsub($amount, $v['pay_amount'], 2), //优惠金额
                            'sale_price' => $v['pay_amount'], //销售金额
                            'amount' => $amount, //商品金额
                            'quantity' => $v['buy_num'], //商品数量
                            'status' => 'active', //商品状态
                        ]

                    ];
                    $order_objects[] = [
                        'obj_type' => 'goods', //对象类型
                        'obj_alias' => '商品', //商品对象名称
                        'bn' => $bn, //商品编号
                        'oid' => strval($v['id']),//子订单号
                        'name' => $name, //子订单名称 普通商品：取子订单商品明细的商品标题
                        'price' => $v['buy_price'], //子订单商品单价 普通商品：取子订单商品明细的商品价格
                        'amount' => $amount, //子订单商品金额
                        'quantity' => $v['buy_num'], //子订单商品数量 普通商品：取子订单商品明细的商品价格
                        'order_items' => $order_items, //子订单商品明细
                    ];
                }

                //
                $params = [
                    'method' => $method,
                    'order_bn' => $order_no, //好好住订单号
                    'status' => 'active',
                    'pay_status' => 1,
                    'ship_status' => 0,
                    'pay_bn' => $payWay, //支付方式编号
                    'createtime' => $order['addtime'],
                    'pmt_goods' => bcsub($order['goods_amount'], $pay, 2), //商品优惠
                    'cost_item' => $order['goods_amount'], //商品总金额
                    'total_amount' => $pay, //订单总额
                    'payed' => $pay, //已付金额
                    'lastmodify' => $order['edittime'],
                    'currency' => 'Cny',
                    'order_objects' => json_encode($order_objects, JSON_UNESCAPED_UNICODE),
                    'member_info' => json_encode(self::MEMBER_INFO, JSON_UNESCAPED_UNICODE),
                    'payments' => json_encode($payments, JSON_UNESCAPED_UNICODE),
                    'consignee' => json_encode($consignee, JSON_UNESCAPED_UNICODE),
                    'pay_time' =>  $order['edittime'], //优惠描述
                ];

                Log::info('处理订单数据', compact('orderInfoList', 'orderGoodsList', 'params'));

                //接口请求
                self::api($params);
            }
        }
    }


    public static function addRefund($refundOrderNo, $order_no, $orderSku)
    {
        $return_product_items = [];
        $return_item = [];
        $total_fee = 0;
        if ($orderSku && ($orderSku['shop_id'] == self::SHOP_ID)) {
            //待发货状态才通知
            $orderInfo = \Biz\model\trade\Order::getOrderInfo($order_no);
            if (! in_array($orderInfo['status'], [\Biz\model\trade\Order::STATUS_WAIT_SEND])) return false;

            $price = $orderSku['pay_amount'];
            $bn = GoodsSku::get('sku_no', ['id' => $orderSku['sku_id']]);
            $name = $orderSku['title'] . " " . $orderSku['sku_desc'];
            $total_fee = bcadd($total_fee, $price, 2);
            $return_product_items[] = [
                'bn' => $bn,//商品编码
                'name' => $name,//商品名称
                'num' => $orderSku['buy_num'],//商品数量
                'price' => $orderSku['pay_amount'],//商品单价
            ];
            $return_item[] = [
                'price' => $orderSku['pay_amount'],
                'oid' => strval($orderSku['id']),
                'modified' => date('Y-m-d H:i:s'),
                'num' => $orderSku['buy_num'],
            ];
        }

        if (empty($return_item)) return false;

        $method = 'ome.aftersalev2.add';

//        $params = [
//            'method' => $method,
//            'return_bn' => $refundOrderNo,
//            'order_bn' => $order_no,
//            'refund_type' => 'apply',//售后类型（return：退货退款申请、refund（退款成功）、apply（仅退款申请）
//            'status' => '1', //1:申请中,2:审核中,3:接受申请,4:完成,5:拒绝,6:已收货
//            'title' => '退款申请',//售后标题
//            'content' => "仅退款 $total_fee 元",//买家填写的售后内容
//            'total_fee' => $total_fee,//申请退款金额
//            'add_time' => time(),//售后申请时间（格式：时间戳）
//            'return_product_items' => json_encode($return_product_items, JSON_UNESCAPED_UNICODE),//售后商品明细 JOSN
//        ];

        $refund_item_list = compact('return_item');
        $refundOrderNo = strval(crc32($refundOrderNo));
        $params = [
            'method' => $method,
            'jsrefund_flag' => 'false',
            'refund_id' => $refundOrderNo,
            'currency' => 'CNY',
            'good_status' => 'BUYER_NOT_RECEIVED',
            'advance_status' => '0',
            'outer_no' => $refundOrderNo,
            'status_old' => '0',
            'tid' => $order_no,
            'has_good_return' => 'false',
            'status' => 'SUCCESS',
            'oid' => '',
            'cs_status' => '1',
            'buyer_account' => '',
            'reason' => '退款申请',
            'date' => date('Y-m-d H:i:s'),
            'refund_fee' => $total_fee,
            't_sent' => '',
            'payment_id' => '2017121421001001920249094997',
            'paycost' => '',
            'refund_item_list' => json_encode($refund_item_list),
            'buyer_nick' => self::MEMBER_INFO['uname'],
            'seller_nick' => 'zhuangzhuang22',
            'created' => date('Y-m-d H:i:s'),
            'good_return_time' => '',
            'modified' => date('Y-m-d H:i:s', time()+8*60*60),
            // 'modified' => date('Y-m-d H:i:s', time()),
            't_begin' => date('Y-m-d H:i:s'),
            'payment_type' => '支付宝',
            'total_fee' => $total_fee,
            'split_seller_fee' => '',
            'refund_type' => 'refund',
            'currency_fee' => $total_fee,
            'refund_phase' => 'onsale',
            'refund_version' => '1530791402292',
            'spider_type' => 'tm_refund_i',
            'source' => 'matrix'
        ];

        //接口请求
        self::api($params);
    }

    public static function api($params)
    {

//        $url = 'http://uatoms.nipponpaint.com.cn/index.php/api';//开发
        $url = 'http://oms.nipponpaint.com.cn/index.php/api';//开发

        $systemParams = [
            'timestamp' => date('Y-m-d H:i:s'),
//            'node_id' => '814690152',//开发
            'node_id' => '3219401061',//正式
            'v' => '1.0',
        ];

        $params = array_merge($systemParams, $params);

        $params['sign'] = self::gen_sign($params);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_VERBOSE, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        $response = curl_exec($ch);

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        Log::info('立邦接口调用结果', compact('params', 'httpCode', 'response'));

    }


}